<?php
namespace common\components\extenders;

use backend\modules\wechat\models\Wechat;
use common\components\helpers\Tree;
use common\models\datas\Cate;
use common\models\datas\CateAttr;
use common\models\datas\Category;
use common\models\datas\Menu;
use frontend\models\datas\Goods;
use frontend\models\datas\Sales;
use yii\base\Component;
use yii\base\Exception;
use yii\db\Query;
use common\components\helpers\Fun;
use EasyWeChat\Foundation\Application;
use yii\web\HttpException;

class CacheManage extends Component
{
    /**
     * @var string $cacheName 缓存存储用的key
     */
    private $cacheName;

    private $fieldName;

    private $site;

    private $wechatId;


    public function setCacheName($cacheName)
    {
        $this->cacheName = $cacheName;
    }

    public function getCacheName()
    {
        return $this->cacheName;
    }

    public function setFieldName($fieldName)
    {
        $this->fieldName = $fieldName;
    }

    public function getFieldName()
    {
        return $this->fieldName;
    }

    public function setSite($site)
    {
        $this->site = $site;
    }


    public function getSite()
    {
        return $this->site;
    }

    public function setWechatId($wechatId)
    {
        $this->wechatId = $wechatId;
    }


    public function getWechatId()
    {
        return $this->wechatId;
    }

    /**
     * 更新缓存方法
     */
    //用于updatecachebehavior中的触发
    public function updateCache()
    {
        if ($this->cacheName !== null) {
            $cache_name = $this->createCacheName();
            if (method_exists($this, '_update' . ucfirst($this->cacheName) . 'Cache')) {
                call_user_func(array($this, '_update' . ucfirst($this->cacheName) . 'Cache'), $cache_name);//call_user_func的第一个参数为被调用的回调函数，第二个为回调函数的参数
            }
        }
    }

    /**
     * 取得缓存方法
     */
    public function findCache()
    {
        if ($this->cacheName !== null) {//若本实例的cachename不为空
            $cache_name = $this->createCacheName();//得到形如：[site]_cachename_[fieldname]_cache
            $array_cache = \Yii::$app->cache->get($cache_name);//取缓存
            if (empty($array_cache)) {//若未取得缓存
                //例如检验本实例中是否存在的_updatemenucache方法
                if (method_exists($this, '_update' . ucfirst($this->cacheName) . 'Cache')) {
                    //调用以上方法，$cache_name为参数，作用是更新缓存
                    call_user_func([$this, '_update' . ucfirst($this->cacheName) . 'Cache'], $cache_name);
                }
                $array_cache = \Yii::$app->cache->get($cache_name);//取缓存
            }
            return $array_cache;
        }
    }

//通过本实例中的site、cachename、fieldname,返回:site_cachename_fieldname_cache
    private function createCacheName()
    {
        $cache_name = !empty($this->site) ? $this->site . '_' : '';
        $cache_name .= $this->cacheName;
        $cache_name .= !empty($this->fieldName) ? '_' . $this->fieldName : '';
        $cache_name .= !empty($this->wechatId) ? '_' . $this->wechatId : '';
        $cache_name .= '_cache';
        return $cache_name;
    }

    /**
     * 后台管理菜单更新缓存
     */
    private function _updateMenuCache($cache_name)
    {//em……目前的系统是每个分店的菜单显示是一样的，后期如果不一致这part也要进行修正
        $query = (new Query())->select('*')->from('{{%menu}}')->where(['<>','display',0]);
        if (!empty($this->fieldName)) $query->andWhere(['module' => $this->fieldName]);
        $rows = $query->orderBy('listorder ASC,id ASC')->indexBy('id')->all(Fun::getSysDb());
        \Yii::$app->cache->set($cache_name, $rows);
    }

    /*
     * 不要破坏原有的重新写一个以树状结构显示的缓存列表
     */
    private function _updateMenutreeCache($cache_name){
        //$query = (new Query())->select('*')->from('{{%menu}}')->where(['<>','display',0]);
        $query = Menu::find()->where(['<>','display',0]);
        if (!empty($this->fieldName)) $query->andWhere(['module' => $this->fieldName]);
        $rows = $query->orderBy('listorder ASC,id ASC')->indexBy('id')->all(Fun::getSysDb());
        //$tree = (new Tree(Fun::asArray($rows,['frontend_ruleoperate'])))->get_jquery_tree_array(0);
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateWebsiteCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%website}}');
        $rows = $query->orderBy('id ASC')->indexBy('domain')->all(Fun::getSiteDatabases());
        \Yii::$app->cache->set($cache_name, $rows);
    }
    private function _updateSiteCache($cache_name)
    {
//        Fun::setSiteDatabases();
        $query = (new Query())->select('*')->from('{{%site}}');
        $rows = $query->orderBy('id ASC')->indexBy('domain')->all();
        $site_array = [];
        foreach ($rows as $k => $v) {//形如:aks=>[]
            //params为config\params
            if (isset(\Yii::$app->params['db'][$k])) $v['db'] = \Yii::$app->params['db'][$k];
            $site_array[$k] = $v;
        }
        \Yii::$app->cache->set($cache_name, $site_array);
    }

    private function _updateIntegralconfigCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%integral_config}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateMessageconfigCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%message_config}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    /**
     * 后台管理菜单更新缓存
     */
    private function _updateWebMenuCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%menu}}');
        $rows = $query->orderBy('listorder ASC,id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateWebCategoryCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%category}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateWebwechatCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%wechat}}');
        $rows = $query->where(['status' => 1])->orderBy('id ASC')->indexBy('web_site_id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    //触屏页面从goods表中筛选分类
    private function _updateCateGoodsCourseCache($cache_name)
    {
        $site_id=Fun::getSiteId();
        $goods_id=Goods::find()->select('cat_id')
            ->where(['type_id'=>1,'is_delete'=>0,'is_shelve'=>1,'site_id'=>$site_id,'is_show'=>1,'is_classroom'=>1])
            ->distinct()->column(Fun::getSiteDb());
        $filter_id=CateAttr::find()->select('cat_id')->where(['site_id'=>$site_id,'mobile_is_show'=>1])->andWhere(['in','cat_id',$goods_id])->indexBy('cat_id')->column();
        $array=$filter_id;
        if(!empty($filter_id)){
            foreach($filter_id as $k=>$v){
                $cate=Cate::findOne($v);
                if($cate!=null){
                    $arrParentIds = explode(',', $cate->arrparent_id);
                    foreach ($arrParentIds as $arrParentId) {
                        if ($arrParentId != 0 && !in_array($arrParentId, $array)) {
                            $array[$arrParentId]=$arrParentId;
                        }
                    }
                }
            }
        }
        $cate=Cate::find()->where(['in','id',$array])->orderBy('id ASC')->indexBy('id')->all();

        \Yii::$app->cache->set($cache_name, $cate);
    }

    /*添加之前项目中的缓存定义*/
    private function _updateCategoryCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%category}}');
        if (!empty($this->fieldName)) $query->where(['module' => $this->fieldName]);
        $rows = $query->orderBy('listorder ASC,id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    /*更新商品分类的缓存*/
    private function _updateCateCache($cache_name){
        $query = (new Query())->select('*')->from('{{%cate}}');//不知道这个分类要怎么缓存？是不是得按照类型来缓存起来,或者将所有记录都缓存
        if (!empty($this->fieldName)) $query->where(['type_id' => $this->fieldName]);
        $rows = $query->orderBy('sort ASC,id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    /*更新商品品牌的缓存*/
    private function _updateBrandCache($cache_name){
        $query = (new Query())->select('*')->from('{{%brand}}');//不知道这个分类要怎么缓存？是不是得按照类型来缓存起来,或者将所有记录都缓存
        $query->where(['is_show' => 1]);
        $rows = $query->orderBy('sort ASC,id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateMechanicCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%mechanic}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all(Fun::getSiteDb());
//        var_dump($rows);die;
        \Yii::$app->cache->set($cache_name, $rows);
    }

//后台
    private function _updateSettingCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%setting}}');
        $rows = $query->orderBy('id ASC')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateMessageconfigitemCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%message_config_item}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateIntegralconfigitemCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%integral_config_item}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    //前台
    private function _updateClassroomCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%classroom}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all(Fun::getSiteDb());
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateCommentinfoCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%comment_info}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all(Fun::getSiteDb());
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateCouponCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%coupon}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all(Fun::getSiteDb());
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateDepartmentCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%department}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all(Fun::getSiteDb());
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateWechatCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%wechat}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all(Fun::getSiteDatabases());
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateWechataccountCache($cache_name){
        $wechats = Wechat::find()->where(['status'=>1])->indexBy('web_site_id')->all();
        $result = [];
        foreach ($wechats as $k=>$wechat){
            $re = [];
            $re['debug'] = true;
            $re['app_id'] = $wechat['key'];
            $re['secret'] = $wechat['secret'];
            $re['token'] = $wechat['token'];
            $re['aes_key'] = $wechat['encoding_aes_key'];
            $re['website_id'] = $wechat['web_site_id'];
            $log['level'] = 'debug';
            $log['file'] = \Yii::getAlias('@wechat/runtime/logs/').$wechat['key'].'/easywechat.log';
            $re['log'] = $log;
            $oauth['scopes'] = ['snsapi_userinfo'];
            $oauth['callback'] = 'http://wechat.doumiaoduo.net/site/oauthcallback';//后期开发或许有什么后缀
            $re['oauth'] = $oauth;
            $wechatpayinfo = $wechat->wechatPayinfo;
            if($wechatpayinfo){
                $payment['merchant_id'] = $wechatpayinfo['merchant_id'];
                $payment['key'] = $wechatpayinfo['key'];
                $payment['cert_path'] = $wechatpayinfo['cert_path'];
                $payment['key_path'] = $wechatpayinfo['key_path'];
                $payment['notify_url'] = $wechatpayinfo['notify_url'];
                $payment['device_info'] = $wechatpayinfo['device_info'];
                $re['payment'] = $payment;
            }
            $re['secret'] = $wechat['key'];
            $result[$k] = $re;
        }
        /*
         * result长这样：Array
        ([21] => Array
                ([debug] => 1[app_id] => wx18945c71289eb28a[secret] => wx18945c71289eb28a[token] => dmiaod2015[aes_key] => 8O4TM4LPaUpJQRfXWdGVx1pO5ZACJdjgl9MpgN8uDbU[website_id] => 21
                 [log] => Array( [level] => debug[file] => D:\www\doumiaoduo_new/wechat/runtime/logs/wx18945c71289eb28a/easywechat.log                        )
                [oauth] => Array([scopes] => Array([0] => snsapi_userinfo)
                [callback] => http://wechat.doumiaoduo.net/site/oauthcallback)
                [payment] => Array([merchant_id] => rr[key] => rr[cert_path] => D:\www\doumiaoduo_new/wechat/web/certs/rrr/apiclient_cert.pem[key_path] =>[notify_url] => r[device_info] => WEB
        )) */
        \Yii::$app->cache->set($cache_name, $result);
    }

    //获取商品分类列表
    public function updateCategorygoodsformobileCache(){
        $site_id = Fun::getSiteId();
        $cate_attr=CateAttr::find()->select(['cat_id'])->where(['mobile_is_show'=>1,'site_id'=>$site_id])->orderBy('mobile_sort asc')->column();
        $category_all=Cate::find()->indexBy('id')->where(['in','id',$cate_attr])->andWhere(['in','type_id',[1,2,3,4]])->asArray()->all();
        return $category_all;
    }

    private function _updateLinkageCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%linkage}}');
        if (!empty($this->fieldName) && $this->fieldName != 0) $query->where(['keyid' => $this->fieldName]);
        $rows = $query->orderBy('id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updatePositionCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%position}}');
        $rows = $query->orderBy('id ASC')->indexBy('key_name')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateAdvertCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%advert}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateAdvertItemCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%advert_item}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateSalesTagsCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%sales_tags}}');
        $rows = $query->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateWebSalesCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%web_sales}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateCategorysalesCache($cache_name)
    {
        $cookies = \Yii::$app->request->cookies;
        $query = (new Query())->select('category_id')->from('{{%sales}}');
        $category_ids = $query->where(['status' => [3, 4], 'is_book' => 1, 'site_id' => $cookies['site_id']])->groupBy('category_id')->all(Fun::getSiteDatabases($cookies['site_id']));
        $categoryId_Yiji = array();
        $categoryId_Erji = array();
        foreach ($category_ids as $category_id) {
            $categoryId_Erji[] = $category_id['category_id'];
            $query = Category::find()->select('arrparentid');
            $strParentId = $query->where(['id' => $category_id['category_id']])->one();
            $arrParentIds = explode(',', $strParentId['arrparentid']);
            foreach ($arrParentIds as $arrParentId) {
                if ($arrParentId != 0 && !in_array($arrParentId, $categoryId_Yiji)) {
                    $categoryId_Yiji[] = $arrParentId;
                }
            }
        }
        $categoryId = array_merge($categoryId_Yiji, $categoryId_Erji);
        $query = Category::find();
        $rows = $query->where(['in', 'id', $categoryId])->asArray()->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateCategorygoodsformobileCache($cache_name){
        $site_id = \Yii::$app->session->get('site_id');
        $cate_attr=CateAttr::find()->select(['cat_id'])->where(['mobile_is_show'=>1,'site_id'=>$site_id])->orderBy('mobile_sort asc')->column();
        $category_all=Cate::find()->indexBy('id')->where(['in','id',$cate_attr])->andWhere(['in','type_id',[1,2,3,4]])->asArray()->all();
        \Yii::$app->cache->set($cache_name,$category_all);
    }

    private function _updateWebSalesAttrCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%web_sales_attr}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateWebSalesTypeAttrCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%web_sales_type_attr}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    private function _updateWechatMenuCache($cache_name)
    {
        $option = \Yii::$app->params['options'];
        $app = new Application($option);
        $menu = $app->menu;
        if($menu){
            $menu = $menu->all()->menu;
            $wechatMenu = !empty($menu) ?$menu['button']: [];
            \Yii::$app->cache->set($cache_name, $wechatMenu);
        }else{
            \Yii::$app->cache->set($cache_name, []);
        }

    }

    private function _updateCardAttrCache($cache_name)
    {
        $query = (new Query())->select('*')->from('{{%card_attr}}');
        $rows = $query->orderBy('id ASC')->indexBy('id')->all();
        \Yii::$app->cache->set($cache_name, $rows);
    }

    /*
     * 微信公众号自定义菜单
     */
    private function _updateCustommenuCache($cache_name)
    {
        if(!empty($this->wechatId)) {
            $wechat = Wechat::findOne($this->wechatId);
            if (!empty($wechat)) {
                $options = [
                    'app_id' => $wechat->key,
                    'secret' => $wechat->secret,
                    'token' => $wechat->token,
                    'aes_key' => $wechat->encoding_aes_key,
                ];
                $app = new Application($options);
                $menu = $app->menu;

                \Yii::error('------menu----');
                \Yii::error($menu);
                try{
                    $wechatMenu = $menu->all();
                    \Yii::$app->cache->set($cache_name, $wechatMenu);
                }catch (\EasyWeChat\Core\Exceptions\HttpException $e){
                    \Yii::error($e->getMessage());
                    \Yii::$app->cache->set($cache_name, []);
                }
//                if($menu){
//                    $wechatMenu = $menu->all() ? $menu->all() : [];
//                    \Yii::$app->cache->set($cache_name, $wechatMenu);
//                }else{
//                    \Yii::$app->cache->set($cache_name, []);
//                }

            }
        }
    }
}
